package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.data.redis.domain.geo.Metrics;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    @Transactional
    public void updateShopById(Shop shop) {
        // 1. 更新数据库
        this.updateById(shop);
        // 2. 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        // int a = 1 / 0;
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1. 判断是否需要距离排序
        int size = SystemConstants.DEFAULT_PAGE_SIZE;
        if(x == null || y == null) {
            Page<Shop> page = this.page(
                new Page<>(current, size),
                new LambdaQueryWrapper<Shop>().eq(Shop::getTypeId, typeId)
            );
            return Result.ok(page.getRecords());
        }
        // 2. 计算分页参数进行查询
        int begin = (current - 1) * size;
        int end = current * size;
        // 3. 进行按照距离查询
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> result = stringRedisTemplate.opsForGeo()
            .search(key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000, Metrics.METERS),
                // 3.1 查询完包含这个点
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
            );
        // 4. 解析出id
        if(result == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = result.getContent();
        // 4.1 截取begin ~ end的部分
        List<Long> ids = new ArrayList<>(size);
        HashMap<String, Distance> map = new HashMap<>(size);
        list.stream().skip(begin).forEach(r -> {
            // 4.2 获取店铺id
            String shopIdStr = r.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3 获取距离
            Distance distance = r.getDistance();
            map.put(shopIdStr, distance);
        });
        // 5. 根据id查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = this.list(
            new LambdaQueryWrapper<Shop>()
                .in(Shop::getId, ids)
                .last("ORDER BY FIELD( id, " + idStr + ")")
        );
        for (Shop shop : shops) {
            Distance distance = map.get(shop.getId().toString());
            shop.setDistance(distance.getValue());
        }
        // 6. 返回
        return Result.ok(shops);
    }
}












